const cp = require('child_process')
const { resolve } = require('path')
const mongoose = require('mongoose')
const Movie = mongoose.model('movie')
const schedule = require('node-schedule')
const sendMail = require('./mailer')

const crawlMovie = async () => {
  const script = resolve(__dirname, '../crawler/movie')
  const child = cp.fork(script, [])
  let invoked = false

  child.on('error', err => {
    if (invoked) return
    invoked = true
    console.log(err)
  })

  child.on('exit', code => {
    if (invoked) return
    invoked = true
    if (code === 0) {
      sendMail({
        to: [
          '956164483@qq.com',
          '807092862@qq.com'
        ],
        subject: '更新完毕',
        html: `
        <a href="http://47.104.24.198/movie-chat/#/movie">最新地址</a>
        `
      }).then(info => {
        console.log(info)
      }).catch(err => {
        console.log(err)
      })
    }
    console.log(`exit code: ${code}`)
    // let err = code === 0 ? null : new Error('exit code ' + code)
  })

  child.on('message', async data => {
    let result = data.result
    let count = 0
    for(let i = 0; i < result.length; i++) {
      let item = result[i]
      let movie = await Movie.findOne({
        m3u8Url: item.m3u8Url
      })
      if (!movie) {
        count++
        movie = new Movie(item)
        await movie.save()
      }
    }
    console.log(`本次入库${count}部`)
  })
}

let rule = new schedule.RecurrenceRule()
rule.dayOfWeek = [0, new schedule.Range(1, 6)]
rule.hour = [12]
rule.minute = [53]
rule.second = [0]

schedule.scheduleJob(rule, () => {
  crawlMovie()
})
